package data

import (
	"fmt"
	"time"
)

type Thread struct {
	Id        uint
	Uuid      string
	Topic     string
	UserId    uint
	CreatedAt time.Time
	Posts     []Post
}

type Post struct {
	Id        uint
	Uuid      string
	Body      string
	UserId    uint
	UserName  string
	ThreadId  uint
	CreatedAt time.Time
}

func (this *Thread) CreatedAtDate() string {
	return this.CreatedAt.Format("Jan 2, 2006 at 3:04pm")
}

func (this *Post) CreatedAtDate() string {
	return this.CreatedAt.Format("Jan 2, 2006 at 3:04pm")
}

func (this *Thread) NumReplies() int {
	return 0
}

func (this *User) CreateThread(topic string) (Thread, error) {
	dbThread := &DbThread{
		Uuid:   createUUID(),
		Topic:  topic,
		UserId: this.Id,
	}
	Gorm.Create(&dbThread)
	thread := Thread{
		Id:        dbThread.ID,
		Uuid:      dbThread.Uuid,
		Topic:     dbThread.Topic,
		UserId:    dbThread.UserId,
		CreatedAt: dbThread.CreatedAt,
	}
	return thread, nil
}

func (this *User) CreatePost(thread Thread, body string) (post Post, err error) {
	dbPost := &DbPost{
		Uuid:     createUUID(),
		Body:     body,
		UserId:   this.Id,
		ThreadId: thread.Id,
	}
	Gorm.Create(&dbPost)
	post = Post{
		Id:        dbPost.ID,
		Uuid:      dbPost.Uuid,
		Body:      dbPost.Body,
		UserId:    dbPost.UserId,
		ThreadId:  dbPost.ThreadId,
		CreatedAt: dbPost.CreatedAt,
	}
	return
}

func Threads() (threads []Thread, err error) {
	t := Thread{}
	var dbThreads []DbThread
	Gorm.Find(&dbThreads)
	for _, v := range dbThreads {
		t.Id = v.ID
		t.Uuid = v.Uuid
		t.Topic = v.Topic
		t.UserId = v.UserId
		t.CreatedAt = v.CreatedAt
		threads = append(threads, t)
	}
	return
}

func (this *Thread) SetPost(userMgr UserMgr) {
	this.Posts = this.GetPosts(userMgr)
}

func (this *Thread) GetPosts(userMgr UserMgr) (posts []Post) {
	var dbPosts []DbPost
	Gorm.Where("thread_id=?", this.Id).Find(&dbPosts)
	var t Post
	for _, v := range dbPosts {
		t.Id = v.ID
		t.Uuid = v.Uuid
		t.Body = v.Body
		t.UserId = v.UserId
		t.ThreadId = v.ThreadId
		t.CreatedAt = v.CreatedAt
		fmt.Println("Thread GetPosts id = ", v.UserId)
		if user := userMgr.GetUser(v.UserId); user != nil {
			t.UserName = user.Name
		}
		posts = append(posts, t)
	}
	fmt.Println("posts: ", posts)
	return
}

func GetThreadByUuid(uuid string) (Thread, error) {
	dbthread := DbThread{}
	Gorm.Where("uuid = ?", uuid).First(&dbthread)
	thread := Thread{
		Id:        dbthread.ID,
		Uuid:      dbthread.Uuid,
		Topic:     dbthread.Topic,
		UserId:    dbthread.UserId,
		CreatedAt: dbthread.CreatedAt,
	}
	return thread, nil
}
